<template>
  <!-------- 新增/编辑植物 -------->
  <div class="update_plan">
    <div class="header">
      <div class="left">
        <p>{{ "新增/编辑植物" }}</p>
        <el-button class="back_btn" @click="handleBack">返回</el-button>
      </div>
    </div>

    <el-form :model="planForm" :rules="rules" ref="ruleFormRef">
      <div class="basically">
        <div class="info">
          <!-- 植物名称 -->
          <el-form-item label="植物名称:" prop="plantName">
            <el-input placeholder="请输入植物名称" v-model="planForm.plantName" />
          </el-form-item>

          <!-- 植物分类 -->
          <el-form-item label="植物分类:" prop="plantTypeId">
            <el-select
              v-model="planForm.plantTypeId"
              placeholder="请选择"
              size="large"
              style="width: 100%"
            >
              <el-option
                v-for="item in categoryList"
                :key="item.id"
                :label="item.plantTypeName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- 科 -->
          <el-form-item label="科:" prop="plantFamilies">
            <el-input  placeholder="请输入科" v-model="planForm.plantFamilies" />
          </el-form-item>

          <!-- 属 -->
          <el-form-item label="属:" prop="plantProperty">
            <el-input  placeholder="请输入属" v-model="planForm.plantProperty" />
          </el-form-item>
        </div>

        <el-form-item prop="plantUrl">
          <!-- 上传照片 -->
          <el-upload
            class="plan-uploader"
            list-type="picture-card"
            action="#"
            accept="image/*"
            :show-file-list="false"
            v-loading="loading"
            :http-request="handleHttpRequest"
            :before-upload="beforeUpload"
          >
            <img
              v-if="planForm.plantUrl"
              :src="planForm.plantUrl"
              alt=""
              srcset=""
            />

            <div v-else class="refer">
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              <span>添加图片</span>
            </div>
          </el-upload>
        </el-form-item>
      </div>

      <!-- 基本特征 -->
      <el-form-item label="基本特征:" prop="plantCharacteristics">
        <el-input
          v-model="planForm.plantCharacteristics"
          placeholder="请输入基本特征"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>

      <!-- 生长习性 -->
      <el-form-item label="生长习性:" prop="palntHabitGrowth">
        <el-input
          v-model="planForm.palntHabitGrowth"
          type="textarea"
          placeholder="请输入生长习性"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>

      <!-- 生态角色 -->
      <el-form-item label="生态角色:" prop="plantRoleEcology">
        <el-input
          v-model="planForm.plantRoleEcology"
          placeholder="请输入生态角色"
          type="textarea"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>

      <!-- 养护需求 -->
      <el-form-item label="养护需求:" prop="palntMaintenanceNeeds">
        <el-input
          v-model="planForm.palntMaintenanceNeeds"
          type="textarea"
          placeholder="请输入养护需求"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>

      <!-- 文化寓意 -->
      <el-form-item label="文化寓意:" prop="palntCulturalImplication">
        <el-input
          v-model="planForm.palntCulturalImplication"
          type="textarea"
          placeholder="请输入文化寓意"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>

      <!-- 繁殖方法 -->
      <el-form-item label="繁殖方法:" prop="palntMethodsReproduction">
        <el-input
          v-model="planForm.palntMethodsReproduction"
          type="textarea"
          placeholder="请输入繁殖方法"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>

      <!-- 病虫害防治 -->
      <el-form-item label="病虫害防治:" prop="plantPestDiseaseControl">
        <el-input
          v-model="planForm.plantPestDiseaseControl"
          type="textarea"
          placeholder="请输入病虫害防治"
          :autosize="{ minRows: 3, maxRows: 6 }"
        />
      </el-form-item>

      <!-- 底部按钮 -->
      <footer>
        <el-button @click="handleBack">取消</el-button>
        <el-button @click="handleSaveBtn('ruleFormRef')" type="primary">
          保存
        </el-button>
      </footer>
    </el-form>
  </div>
</template>

<script setup>
import { onMounted, ref } from "vue";
// 上传接口
import { reqUploadFiles } from "@/api/FileUploads";

// 后端接口
import { addPlans, updatePlans } from "@/api/plans";
import { ElMessage } from "element-plus";

const props = defineProps({
  // 分类数据
  categoryList: {
    type: Array,
    default: () => [],
  },
  // 要修改的数据
  editItemData: {
    type: Object,
    default: () => {},
  },
});

const planForm = ref({}); // 表单信息数据
const loading = ref(false); // 上传的加载状态
let isAddPlan = ref(true); // 是否是添加状态

// 表单验证
const rules = ref({
  plantName: [
    { required: true, message: "请输入植物名称", trigger: "change" },
    { max:10, message: "最大长度为10个字符", trigger: "change" }
  ],
  plantTypeId: [
    { required: true, message: "请选择植物分类", trigger: "change" },
  ],
  plantFamilies: [
    { required: true, message: "请输入科", trigger: "change" },
    { max:10, message: "最大长度为10个字符", trigger: "change" }
  ],
  plantProperty: [
    { required: true, message: "请输入属", trigger: "change" },
    { max:10, message: "最大长度为10个字符", trigger: "change" }

],
  plantUrl: [{ required: true, message: "请上传植物图片", trigger: "change" }],
  
});

const emits = defineEmits(["ShowHidePlant"]);

const ruleFormRef = ref(null); // 表单ref

onMounted(() => {
  // 有修改数据时
  if (props.editItemData) {
    planForm.value = { ...props.editItemData }; // 赋值数据
    isAddPlan.value = false; // 设置添加状态为false
    console.log(typeof planForm.value.plantTypeId);
    
  }
});

/** 上传之前 **/
const beforeUpload = (file) => {
  const alows = ["image/jpeg", "image/png", "image/gif", "image/jpg"];

  if (alows.indexOf(file.type) === -1) {
    ElMessage({ type: "error", message: "请上传图片格式" });
    return false;
  }

  return true;
};

/** 覆盖默认上传 **/
const handleHttpRequest = (options) => {
  try {
    let formData = new FormData();
    formData.append("files", options.file);
    formData.append("uploadName", "plant/image");

    loading.value = true; // 开启加载状态

    reqUploadFiles(formData).then((res) => {
      planForm.value.plantUrl = res.urls; // 赋值图片地址
      loading.value = false; // 关门加载状态

      ruleFormRef.value.validateField('plantUrl') // 校验图片上传状态

    });
  } catch (error) {}
};

/** 保存 **/
const handleSaveBtn = () => {
  ruleFormRef.value.validate(async (valid, fields) => {
    if (valid) {
      // 当是添加时
      if (isAddPlan.value) {
        await addPlans([planForm.value]);
      } else {
        // 修改接口
        await updatePlans(planForm.value);
      }

      ElMessage({ type: "success", message: "操作成功！！" });
      handleBack(); // 返回
    } else {
      console.log("error submit!", fields);
    }
  });
};

/** 返回 */
const handleBack = () => {
  emits("ShowHidePlant", false);
};
</script>

<style lang="scss" scoped>
.update_plan {
  width: 100%;
  min-width: 300px;
  background-color: #fff;
  border-radius: 10px 10px 10px 10px;
  padding: 0 10px 20px;
  min-height: 780px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 78px;
    padding: 0 32px;
    color: #696969;
    font-size: 18px;
    border-bottom: 1px solid #ccc;

    .left {
      display: flex;
      width: 100%;
      justify-content: space-between;
      align-items: center;

      p {
        color: #343957;
        font-size: 22px;
      }

      button {
        font-size: 14px;
        border-radius: 6px 6px 6px 6px;
        border: 1px solid #5974ff;
        color: #5974ff;

        &:hover {
          background: none;
          opacity: 0.8;
        }
      }
    }
  }

  .el-form {
    max-width: 838px;
    margin: 48px auto 0;

    ::v-deep(.el-form-item) {
      .el-form-item__label {
        width: 87px;
      }

      .el-input__wrapper {
        box-shadow: 0 0 0 1px #c2c2c2 inset;
      }

      .el-textarea__inner {
        resize: none;
        box-shadow: 0 0 0 1px #c2c2c2 inset;
      }
    }

    .basically {
      display: flex;

      .info {
        width: 400px;
        margin-right: 120px;
      }

      /**上传 */
      .plan-uploader {
        height: 160px;

        img {
          width: 100%;
          height: 100%;
        }

        ::v-deep(.el-upload--picture-card) {
          border-radius: 10px 10px 10px 10px;
          width: 230px;
          height: 160px;
          background: #fff;
          border-color: #444b7481;
          border-width: 2px;
          &:hover {
            border-color: #5974ff;
          }

          .refer {
            color: #5974ff;
            text-align: center;
            i {
              font-size: 18px;
            }
            span {
              display: block;
              font-size: 14px;
            }
          }
        }
      }
    }

    footer {
      margin-top: 60px;
      button {
        padding: 0;
        width: 108px;
        height: 40px;
        border-radius: 6px 6px 6px 6px;
        border: 1px solid #5974ff;
        font-size: 14px;
        color: #5974ff;

        & + button {
          margin-left: 20px;
        }

        &:hover,
        &:focus {
          background: none;
          opacity: 0.8;
        }

        &.el-button--primary {
          color: #fff;
          border: 0;
          background: #5974ff;
          &:hover,
          &:focus {
            background: #5974ff;
            opacity: 0.8;
          }
        }
      }
    }
  }
}
</style>
